package com.haier.cloudremote;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import javax.mail.internet.NewsAddress;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.haier.cloudremote.common.RemoteManager;
import com.haier.cloudremote.common.SLog;
import com.haier.cloudremote.common.TroubleShooting;
import com.haier.cloudremote.common.XmlParser;
import com.haier.cloudremote.db.DbAdapter;
import com.haier.cloudremote.model.KeyInfo;
import com.haier.cloudremote.protocal.CAEProtocal;
import com.haier.cloudremote.util.FileUtil;

public class StudyActivity extends Activity {

	private StringBuffer debugBuffer = null;// 记录debug按键

	// 以下为线程通信所用的常量
	private static final int GET_STUDY_STATE_FAIL = 10001;
	private static final int GET_STUDY_STATE_OK = 10002;
	private static final int PREPARE_STUDY_OK = 10003;
	private static final int CRB_NOT_FOUND = 10004;
	private static final int UNKNOW_ERROR = 10005;
	private static final int CANNOT_CONNECT_CAE = 10006;
	private static final int CHECKED_KEY_ISTV = 10007;
	private static final int STUDY_KEY_ONCEOK = 10010;
	private static final int STUDY_KEY_TWICEOK = 10011;
	private static final int CANT_CONNECT_CAE = 10012;
	private static final int CONNECT_SHUTDOWN = 10013;
	private static final int NO_RESPONDING = 10014;
	private static final int FINISH_STUDY_OK = 10015;
	private static final int CRB_STUDY_AGAIN = 10017;// 返回1006，重发按键
	private static final int EXCEPTION_FINISH_STUDY = 10020;// 异常结束学习

	private LinearLayout[] line_layout;
	private ImageView[] ok_img;
	private TextView[] intro_text;
	private LinearLayout specialKeyLayout1, specialKeyLayout2;
	private ImageView specialImg1, specialImg2;
	private ProgressDialog mpDialog;

	// 记录上次学习的键值及序号
	private int lastStudyKey = 0;
	private int lastStudyIndex = 0;

	private Handler viewHandler, preHandler;
	// 按键列表
	public ArrayList<KeyInfo> keyInfos, keyInfos1, keyInfos2, keyInfos_extend;
	private XmlResourceParser xrp;// 解析按键列表用

	// 以下保存CAE返回的键值
	private int keyCode1, keyCode2;

	// 按键学习的提示文字
	private String[] keyIntroText, keyIntroText2;

	private int currPageNum = -1;

	// 是否已经学习完成
	private Boolean isInStudy = false;
	// 标志是否找到了得到的按键
	private Boolean isFindLastKey = false;

	// 以下为用到的线程
	private Thread getStateThread, prapareThread, onceStudyThread,
			twiceStudyThread;
	private Boolean isActivityAlive = true;

	private DbAdapter dbAdapter;
	
	private Bitmap bgbm;// 背景图片
	
	private Timer introTimer = new Timer();// 定时器，定时显示错误提示，1s后提示重学按键

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		SLog.d("ssc", "StudyActivity-----------onCreate()");
		setContentView(R.layout.study);

		ActivityStackControlUtil.add(this);

		mpDialog = new ProgressDialog(StudyActivity.this);
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mpDialog.setMessage("正在连接CRB设备");
		mpDialog.setIndeterminate(false);
		mpDialog.setCancelable(true);

		preHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case PREPARE_STUDY_OK:// 已准备好开始学习
					SLog.d("ssc", "已准备好开始学习preHandler");
					isInStudy = true;
					SLog.d("ssc", "isInStudy==" + isInStudy);
					mpDialog.dismiss();
					studyTheKeyOnce(lastStudyIndex);

					RemoteManager.setStudyState(StudyActivity.this, false);
					break;
				case CRB_NOT_FOUND:
				case UNKNOW_ERROR:
				case CANNOT_CONNECT_CAE:
					mpDialog.setMessage(getResources().getString(R.string.preparestudy_fail));
					mpDialog.setOnCancelListener(new OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface dialog) {
							// TODO Auto-generated method stub
							StudyActivity.this.finish();
						}
					});
					break;

				}
			}

		};

		viewHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case CRB_NOT_FOUND:// 找不到CRB设备
					SLog.d("ssc", "找不到CRB设备");
					if (lastStudyIndex < intro_text.length) {
						intro_text[lastStudyIndex]
								.setText(R.string.study_crbnotfound);
						intro_text[lastStudyIndex].setVisibility(View.VISIBLE);
						
					}
					break;
				case UNKNOW_ERROR:// 未知错误
					SLog.d("ssc", "未知错误");
					if (0 < lastStudyIndex
							&& lastStudyIndex < intro_text.length) {
						intro_text[lastStudyIndex]
								.setText(R.string.study_unknowerror);
						intro_text[lastStudyIndex].setVisibility(View.VISIBLE);
					}
					break;
				case CANNOT_CONNECT_CAE:// 连接不上CAE
					SLog.d("ssc", "连接不上CAE");
					if (0 < lastStudyIndex
							&& lastStudyIndex < intro_text.length) {
						intro_text[lastStudyIndex]
								.setText(R.string.study_cannotconnectcae);
						intro_text[lastStudyIndex].setVisibility(View.VISIBLE);
					}
					break;
				case CONNECT_SHUTDOWN:// 与CAE的连接断开，重学按键
					if (0 < lastStudyIndex
							&& lastStudyIndex < intro_text.length) {
						intro_text[lastStudyIndex]
								.setText(R.string.study_connectshutdown);
						intro_text[lastStudyIndex].setVisibility(View.VISIBLE);
					}
					break;
				case NO_RESPONDING:// 超过3秒未收到CRB回应（CRB出错，或者用户未按键，提示用户按键）
					if (0 < lastStudyIndex
							&& lastStudyIndex < intro_text.length) {
						intro_text[lastStudyIndex]
								.setText(R.string.study_no_responding);
						intro_text[lastStudyIndex].setVisibility(View.VISIBLE);
					}
					break;
				case CHECKED_KEY_ISTV:// 用户按键为TV按键
					SLog.d("ssc", "用户按键为TV按键");
					Toast.makeText(
							StudyActivity.this,
							getResources()
									.getString(R.string.pls_check_stb_key),
							Toast.LENGTH_SHORT).show();
					break;

				case STUDY_KEY_ONCEOK:// 第一次学习完成
					SLog.d("ssc", "第一次学习完成");
					if (keyInfos.size() > lastStudyIndex) {
						studyTheKeyTwice(lastStudyIndex);
					}

					break;
				case STUDY_KEY_TWICEOK:// 第二次学习完成
					
					if (keyCode1 == keyCode2) {
						SLog.d("ssc", "第二次学习完成");
						intro_text[lastStudyIndex]
								.setVisibility(View.INVISIBLE);
						line_layout[lastStudyIndex].setBackgroundDrawable(null);
						ok_img[lastStudyIndex]
								.setImageResource(R.drawable.study_okimg);
						ok_img[lastStudyIndex].setVisibility(View.VISIBLE);

						// 修改DB中该键的学习状态
						SLog.d("ssc", "修改DB中该键的学习状态");
						dbAdapter.open();
						dbAdapter.changeState(keyInfos.get(lastStudyIndex)
								.getKeyCode(), 1);
						dbAdapter.close();

						lastStudyIndex++;
						if (currPageNum == 0) {// 第一页
							if (lastStudyIndex < keyInfos1.size()) {// 第一页未学完
								// 学习lastStudyIndex按键
								studyTheKeyOnce(lastStudyIndex);
							} else {// 第一页学完了
									// 学习第二页
								jumpToStudy2(0);
								studyTheKeyOnce(lastStudyIndex);
							}
						} else if (currPageNum == 1) {// 第二页
							if (lastStudyIndex < keyInfos2.size()) {// 第二页未学完
								// 学习lastStudyIndex按键
								studyTheKeyOnce(lastStudyIndex);
							} else {// 第二页学完了
								jumpToExtend(0);
							}
						} else if (currPageNum == 2) {// 扩展页
							specialImg2
									.setImageResource(R.drawable.specialstudy_key1);
							specialKeyLayout2.setBackgroundDrawable(null);
							finishStudy();
							RemoteManager.setStudyState(StudyActivity.this,
									true);
							Intent intent = new Intent();
							intent.setClass(StudyActivity.this,
									FinishActivity.class);
							startActivity(intent);
							lastStudyIndex = -1;
						}

					} else {// 重学此按键
						if (keyInfos.size() > lastStudyIndex) {
							studyTheKeyOnce(lastStudyIndex);
							Toast.makeText(StudyActivity.this,
									"两次学习的按键不一致，请重学此按键", Toast.LENGTH_SHORT)
									.show();
						}

					}

					break;
				case CANT_CONNECT_CAE:// 连接不上CAE，正在重试
					if (lastStudyIndex < intro_text.length) {
						intro_text[lastStudyIndex]
								.setText(R.string.cant_connect_cae);
					}
					break;
				case FINISH_STUDY_OK:// 学习完成
					isInStudy = false;
					SLog.d("ssc", "isInStudy==" + isInStudy);
					break;

				case EXCEPTION_FINISH_STUDY:
					break;
				default:
					break;
				}
			}

		};

		isActivityAlive = true;

		getKeyListsFromXML();
		
		bgbm = FileUtil.readBitMap(this, R.drawable.studybg);
		
		// 学习初始化
		studyInit();
		
	}

	/**
	 * 学习初始化
	 * 1.获取进度
	 * 2.查找该按键所在的位置
	 * 3.开始学习
	 */
	private void studyInit() {
		// TODO Auto-generated method stub
		studyFirstPage(0);
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			lastStudyKey = bundle.getInt("lastStudyKey");
		}
		if (lastStudyKey != 0) {// 获取到进度
			// 从上次学习的按键后开始学习
			int keySize1 = keyInfos1.size();
			SLog.d("ssc", "在第一页里面找 keySize1==" + keySize1);
			SLog.d("ssc", "currPageNum==" + currPageNum);
			for (int i = 0; i < keySize1; i++) {
				KeyInfo keyInfo = keyInfos1.get(i);
				if (keyInfo.getKeyCode() == lastStudyKey) {
					SLog.d("ssc", "找到了i==" + i);
					isFindLastKey = true;
					studyFirstPage(i);
					prapareStudy();
					break;
				} else {
					SLog.d("ssc", "keyInfo.getState()：i==" + keyInfo.getState()
							+ ":" + i);
					ok_img[i].setVisibility(View.VISIBLE);
					if (keyInfo.getState() == 0) {
						ok_img[i].setImageResource(R.drawable.nostudykey);
					} else {
						ok_img[i].setImageResource(R.drawable.study_okimg);
					}

				}
			}
			SLog.d("ssc", "currPageNum==" + currPageNum);
			if (!isFindLastKey) {
				int keySize2 = keyInfos2.size();
				SLog.d("ssc", "在第二页里面找 keySize2==" + keySize2);
				for (int i = 0; i < keySize2; i++) {
					if (keyInfos2.get(i).getKeyCode() == lastStudyKey) {
						SLog.d("ssc", "找到了i==" + i);
						isFindLastKey = true;
						jumpToStudy2(i);
						prapareStudy();
						break;
					}
				}
				SLog.d("ssc", "currPageNum==" + currPageNum);
				if (!isFindLastKey) {
					int keySize_extend = keyInfos_extend.size();
					SLog.d("ssc", "在扩展页里面找 keySize_extend==" + keySize_extend);
					for (int i = 0; i < keySize_extend; i++) {
						if (keyInfos_extend.get(i).getKeyCode() == lastStudyKey) {
							SLog.d("ssc", "找到了i==" + i);
							isFindLastKey = true;
							jumpToExtend(i);
							prapareStudy();
							break;
						}
					}
					SLog.d("ssc", "currPageNum==" + currPageNum);
					if (!isFindLastKey) {
						SLog.d("ssc", "扩展页也未找到");
						for (int j = 0; j < ok_img.length; j++) {
							ok_img[j].setVisibility(View.INVISIBLE);
						}
						studyFirstPage(0);
						prapareStudy();
					}
				}
			}
		} else {// 未获取到
			studyFirstPage(0);
			prapareStudy();
		}
	}

	/**
	 * 学习第一页
	 * 
	 * @param i 从第一页第i个按键开始学习
	 */
	private void studyFirstPage(int i) {
		// TODO Auto-generated method stub
		setContentView(R.layout.study);
		
		currPageNum = 0;
		keyIntroText = getResources().getStringArray(R.array.study_intro_text);
		keyIntroText2 = getResources()
				.getStringArray(R.array.study2_intro_text);
		keyInfos = keyInfos1;

		viewInit();

		lastStudyIndex = i;
		int key_size = keyInfos.size();
		for (int j = 0; j < key_size; j++) {
			if (j < i) {
				ok_img[j].setVisibility(View.VISIBLE);
				line_layout[j].setBackgroundDrawable(null);
				intro_text[j].setVisibility(View.GONE);

				if (keyInfos.get(j).getState() == 0) {
					ok_img[j].setImageResource(R.drawable.nostudykey);
				} else {
					ok_img[j].setImageResource(R.drawable.study_okimg);
				}

			}
		}

	}

	/**
	 * 获取资源中的按键编码XML文件并对文件进行解析，获取到所有键的列表
	 */
	private void getKeyListsFromXML() {
		// TODO Auto-generated method stub
		dbAdapter = new DbAdapter(this);
		
		dbAdapter.open();
		Cursor cursor = dbAdapter.getKeyOfPage(0);

		if (cursor.getCount() > 0) {// DB中有数据
			SLog.d("ssc", "查询DB 第一页 count==" + cursor.getCount());
			keyInfos1 = new ArrayList<KeyInfo>();
			KeyInfo keyInfo;
			while (cursor.moveToNext()) {// 获得第一页按键列表
				keyInfo = new KeyInfo();
				keyInfo.setKeyCode(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_KEYCODE)));
				keyInfo.setKeyName(cursor.getString(cursor
						.getColumnIndex(DbAdapter.F_KEYNAME)));
				keyInfo.setPageNum(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_PAGENUM)));
				keyInfo.setState(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_STATE)));
				keyInfos1.add(keyInfo);
			}
			dbAdapter.open();
			cursor = dbAdapter.getKeyOfPage(1);
			keyInfos2 = new ArrayList<KeyInfo>();
			while (cursor.moveToNext()) {// 获得第二页按键列表
				keyInfo = new KeyInfo();
				keyInfo.setKeyCode(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_KEYCODE)));
				keyInfo.setKeyName(cursor.getString(cursor
						.getColumnIndex(DbAdapter.F_KEYNAME)));
				keyInfo.setPageNum(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_PAGENUM)));
				keyInfo.setState(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_STATE)));
				keyInfos2.add(keyInfo);
			}
			dbAdapter.close();
			dbAdapter.open();
			cursor = dbAdapter.getKeyOfPage(2);
			keyInfos_extend = new ArrayList<KeyInfo>();
			while (cursor.moveToNext()) {// 获得扩展页按键列表
				keyInfo = new KeyInfo();
				keyInfo.setKeyCode(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_KEYCODE)));
				keyInfo.setKeyName(cursor.getString(cursor
						.getColumnIndex(DbAdapter.F_KEYNAME)));
				keyInfo.setPageNum(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_PAGENUM)));
				keyInfo.setState(cursor.getInt(cursor
						.getColumnIndex(DbAdapter.F_STATE)));
				keyInfos_extend.add(keyInfo);
			}
			cursor.close();
			dbAdapter.close();
		} else {// DB无数据
			dbAdapter.close();
			
			xrp = this.getResources().getXml(R.xml.ssckeycode);
			keyInfos1 = XmlParser.getKeyList(xrp, 0);
			int key_size1 = keyInfos1.size();
			for (int i = 0; i < key_size1; i++) {// 存DB
				dbAdapter.open();
				dbAdapter.insertKey(keyInfos1.get(i));
				dbAdapter.close();
			}
			xrp = getResources().getXml(R.xml.ssckeycode2);
			keyInfos2 = XmlParser.getKeyList(xrp, 1);
			int key_size2 = keyInfos2.size();
			for (int i = 0; i < key_size2; i++) {// 存DB
				dbAdapter.open();
				dbAdapter.insertKey(keyInfos2.get(i));
				dbAdapter.close();
			}
			xrp = getResources().getXml(R.xml.extendkey);
			keyInfos_extend = XmlParser.getKeyList(xrp, 2);
			int key_size_extend = keyInfos_extend.size();
			for (int i = 0; i < key_size_extend; i++) {// 存DB
				dbAdapter.open();
				dbAdapter.insertKey(keyInfos_extend.get(i));
				dbAdapter.close();
			}
		}
		
	}

	/**
	 * 开始学习
	 */
	private void prapareStudy() {
		// TODO Auto-generated method stub
		SLog.d("ssc", "prapareStudy--------------------");
		mpDialog.show();
		prapareThread = new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				int startReturn;
				while (isActivityAlive) {
					startReturn = CAEProtocal.startStudy();
					SLog.d("ssc", "startReturn==" + startReturn);
					if (startReturn == 1002) {// CAE准备好开始学习
						preHandler.sendEmptyMessage(PREPARE_STUDY_OK);
						break;
					} else {// 准备学习失败
						switch (startReturn) {
						case -1100:// CRB 设备未找到
							preHandler.sendEmptyMessage(CRB_NOT_FOUND);
							break;
						case -1000:// 其他错误
							preHandler.sendEmptyMessage(UNKNOW_ERROR);
							break;
						case -2000:// socket no create
							preHandler.sendEmptyMessage(CANNOT_CONNECT_CAE);
							break;
						default:
							break;
						}
						try {
							sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							if(e!=null){
								SLog.e("ssc", "StudyActivity----------555-------e=="+e.getMessage());
							}
						}
					}

				}

			}

		};
		prapareThread.start();
	}

	/**
	 * 第一次学习按键key
	 * 
	 * @param keyIndex
	 */
	private void studyTheKeyOnce(int keyIndex) {
		// TODO Auto-generated method stub
		SLog.d("ssc", "studyTheKeyOnce--------------------");
		final KeyInfo keyInfo = keyInfos.get(keyIndex);
		if (currPageNum == 2) {
			specialKeyLayout1
					.setBackgroundResource(R.drawable.specialstudy_keybg);
			specialKeyLayout2.setBackgroundDrawable(null);
		} else {
			line_layout[keyIndex].setBackgroundResource(R.drawable.study_first);
			SLog.d("ssc", "lastStudyIndex==" + lastStudyIndex);
			SLog.d("ssc", "keyIntroText[lastStudyIndex]=="
					+ keyIntroText[lastStudyIndex]);
			intro_text[keyIndex].setText(keyIntroText[lastStudyIndex]);
			intro_text[keyIndex].setVisibility(View.VISIBLE);
		}

		onceStudyThread = new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				Boolean isSendKey = true;
				Boolean isReturnKey = true;
				while (isInStudy && isActivityAlive) {
					isReturnKey = false;
					SLog.d("ssc", "第一次学习");
					int studyReturn_key = CAEProtocal.studyOfKey(
							keyInfo.getKeyCode(), isSendKey);
					SLog.d("ssc", "studyReturn_key===" + studyReturn_key);
					switch (studyReturn_key) {
					case 1004:// 1004 收到的是TV按键，需要UI提示 用户操作STB按键
						System.out.println("收到的是TV按键，继续等待。。。");

						viewHandler.sendEmptyMessage(CHECKED_KEY_ISTV);
						break;
					case 1005:// 超过3秒未收到CRB回应（CRB出错，或者用户未按键，提示用户按键）
						// 提示用户重新插拔CRB
						viewHandler.sendEmptyMessage(NO_RESPONDING);
						break;
					case 1006:// CRB异常，需重发按键
						viewHandler.sendEmptyMessage(CRB_STUDY_AGAIN);
						break;
					case -1100:// CRB 设备未找到
						viewHandler.sendEmptyMessage(CRB_NOT_FOUND);
						break;
					case -1000:// -1000 其他错误
						viewHandler.sendEmptyMessage(UNKNOW_ERROR);
						break;
					case -2000:// socket建立失败
						viewHandler.sendEmptyMessage(CANT_CONNECT_CAE);
						break;
					case -2001:// 与CAE的socket连接中断
						viewHandler.sendEmptyMessage(CONNECT_SHUTDOWN);
						break;
					case 1003:
						isInStudy = false;
						viewHandler.sendEmptyMessage(EXCEPTION_FINISH_STUDY);
						break;
					default:// 成功返回键值
						isReturnKey = true;
						break;
					}

					if (isReturnKey) {// 成功返回键值
						if (studyReturn_key == 1002) {
							preHandler.sendEmptyMessage(PREPARE_STUDY_OK);
						} else {
							keyCode1 = studyReturn_key;
							viewHandler.sendEmptyMessage(STUDY_KEY_ONCEOK);
						}

						break;
					}

					try {
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						if(e!=null){
							SLog.e("ssc", "StudyActivity----------654-------e=="+e.getMessage());
						}
					}
				}

			}

		};
		onceStudyThread.start();
	}

	/**
	 * 第二次学习按键key
	 * 
	 * @param keyIndex
	 */
	private void studyTheKeyTwice(int keyIndex) {
		// TODO Auto-generated method stub
		final KeyInfo keyInfo = keyInfos.get(keyIndex);
		if (currPageNum == 2) {
			specialKeyLayout1.setBackgroundDrawable(null);
			specialImg1.setImageResource(R.drawable.specialstudy_key1);
			specialKeyLayout2
					.setBackgroundResource(R.drawable.specialstudy_keybg);
		} else {
			line_layout[keyIndex]
					.setBackgroundResource(R.drawable.study_second);
			intro_text[keyIndex].setText(keyIntroText2[lastStudyIndex]);
		}
		twiceStudyThread = new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				Boolean isSendKey = true;
				Boolean isReturnKey = true;
				Boolean isFinishStudy = false;
				while (isInStudy && isActivityAlive) {
					isReturnKey = false;
					SLog.d("ssc", "第二次学习");
					int studyReturn_key = CAEProtocal.studyOfKey(
							keyInfo.getKeyCode(), isSendKey);
					SLog.d("ssc", "studyReturn_key===" + studyReturn_key);
					switch (studyReturn_key) {
					case 1004:// 1004 收到的是TV按键，需要UI提示 用户操作STB按键
						isSendKey = false;
						viewHandler.sendEmptyMessage(CHECKED_KEY_ISTV);
						break;
					case 1005:// 超过3秒未收到CRB回应（CRB出错，或者用户未按键，提示用户按键）
						// 提示用户重新插拔CRB
						isSendKey = false;
						viewHandler.sendEmptyMessage(NO_RESPONDING);
						break;
					case 1006:// CRB异常，需重发按键
						isSendKey = true;
						viewHandler.sendEmptyMessage(CRB_STUDY_AGAIN);
						break;
					case -1100:// CRB 设备未找到
						isSendKey = true;
						viewHandler.sendEmptyMessage(CRB_NOT_FOUND);
						break;
					case -1000:// -1000 其他错误
						isSendKey = true;
						viewHandler.sendEmptyMessage(UNKNOW_ERROR);
						break;
					case -2000:// socket建立失败
						isSendKey = true;
						viewHandler.sendEmptyMessage(CANT_CONNECT_CAE);
						break;
					case -2001:// 与CAE的socket连接中断
						isSendKey = true;
						viewHandler.sendEmptyMessage(CONNECT_SHUTDOWN);
						break;
					case 1003:
						isFinishStudy = true;
						viewHandler.sendEmptyMessage(EXCEPTION_FINISH_STUDY);
						break;
					default:// 成功返回键值
						isReturnKey = true;
						break;
					}

					if (isFinishStudy) {
						break;
					}
					if (isReturnKey) {// 成功返回键值
						keyCode2 = studyReturn_key;
						viewHandler.sendEmptyMessage(STUDY_KEY_TWICEOK);
						break;
					}

					try {
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						if(e!=null){
							SLog.e("ssc", "StudyActivity----------555-------e=="+e.getMessage());
						}
					}
				}

			}

		};
		twiceStudyThread.start();
	}

	/**
	 * 初始化界面控件
	 */
	private void viewInit() {
		// TODO Auto-generated method stub
		line_layout = new LinearLayout[13];
		ok_img = new ImageView[13];
		intro_text = new TextView[13];
		
		findViewById(R.id.study_layout).setBackgroundDrawable(new BitmapDrawable(bgbm));

		line_layout[0] = (LinearLayout) findViewById(R.id.study1_line0_layout);
		line_layout[1] = (LinearLayout) findViewById(R.id.study1_line1_layout);
		line_layout[2] = (LinearLayout) findViewById(R.id.study1_line2_layout);
		line_layout[3] = (LinearLayout) findViewById(R.id.study1_line3_layout);
		line_layout[4] = (LinearLayout) findViewById(R.id.study1_line4_layout);
		line_layout[5] = (LinearLayout) findViewById(R.id.study1_line5_layout);
		line_layout[6] = (LinearLayout) findViewById(R.id.study1_line6_layout);
		line_layout[7] = (LinearLayout) findViewById(R.id.study1_line7_layout);
		line_layout[8] = (LinearLayout) findViewById(R.id.study1_line8_layout);
		line_layout[9] = (LinearLayout) findViewById(R.id.study1_line9_layout);
		line_layout[10] = (LinearLayout) findViewById(R.id.study1_line10_layout);
		line_layout[11] = (LinearLayout) findViewById(R.id.study1_line11_layout);
		line_layout[12] = (LinearLayout) findViewById(R.id.study1_line12_layout);

		ok_img[0] = (ImageView) findViewById(R.id.study1_okImg0);
		ok_img[1] = (ImageView) findViewById(R.id.study1_okImg1);
		ok_img[2] = (ImageView) findViewById(R.id.study1_okImg2);
		ok_img[3] = (ImageView) findViewById(R.id.study1_okImg3);
		ok_img[4] = (ImageView) findViewById(R.id.study1_okImg4);
		ok_img[5] = (ImageView) findViewById(R.id.study1_okImg5);
		ok_img[6] = (ImageView) findViewById(R.id.study1_okImg6);
		ok_img[7] = (ImageView) findViewById(R.id.study1_okImg7);
		ok_img[8] = (ImageView) findViewById(R.id.study1_okImg8);
		ok_img[9] = (ImageView) findViewById(R.id.study1_okImg9);
		ok_img[10] = (ImageView) findViewById(R.id.study1_okImg10);
		ok_img[11] = (ImageView) findViewById(R.id.study1_okImg11);
		ok_img[12] = (ImageView) findViewById(R.id.study1_okImg12);

		intro_text[0] = (TextView) findViewById(R.id.study1_introText0);
		intro_text[1] = (TextView) findViewById(R.id.study1_introText1);
		intro_text[2] = (TextView) findViewById(R.id.study1_introText2);
		intro_text[3] = (TextView) findViewById(R.id.study1_introText3);
		intro_text[4] = (TextView) findViewById(R.id.study1_introText4);
		intro_text[5] = (TextView) findViewById(R.id.study1_introText5);
		intro_text[6] = (TextView) findViewById(R.id.study1_introText6);
		intro_text[7] = (TextView) findViewById(R.id.study1_introText7);
		intro_text[8] = (TextView) findViewById(R.id.study1_introText8);
		intro_text[9] = (TextView) findViewById(R.id.study1_introText9);
		intro_text[10] = (TextView) findViewById(R.id.study1_introText10);
		intro_text[11] = (TextView) findViewById(R.id.study1_introText11);
		intro_text[12] = (TextView) findViewById(R.id.study1_introText12);

	}

	/**
	 * 跳转到第二页
	 * 
	 * @param i
	 *            当前学习按键在第二页中的序号
	 */
	private void jumpToStudy2(int i) {
		// TODO Auto-generated method stub
		setContentView(R.layout.study2);
		currPageNum = 1;
		lastStudyIndex = i;
		// 提示文字
		keyIntroText = getResources().getStringArray(R.array.study_intro_text2);
		keyIntroText2 = getResources().getStringArray(
				R.array.study2_intro_text2);
		keyInfos = keyInfos2;

		viewInit2();

		int key_size = keyInfos.size();
		SLog.d("ssc", "未学完");
		for (int j = 0; j < key_size; j++) {
			if (j < i) {
				KeyInfo keyInfo = keyInfos.get(j);
				if (keyInfo.getState() == 0) {
					ok_img[j].setImageResource(R.drawable.nostudykey);
				} else {
					ok_img[j].setImageResource(R.drawable.study_okimg);
				}

				ok_img[j].setVisibility(View.VISIBLE);
				line_layout[j].setBackgroundDrawable(null);
				intro_text[j].setVisibility(View.GONE);
			}
		}

		// }

	}

	private void viewInit2() {
		// TODO Auto-generated method stub
		line_layout = new LinearLayout[12];
		ok_img = new ImageView[12];
		intro_text = new TextView[12];		

		findViewById(R.id.study2_layout).setBackgroundDrawable(new BitmapDrawable(bgbm));
		
		line_layout[0] = (LinearLayout) findViewById(R.id.study2_line0_layout);
		line_layout[1] = (LinearLayout) findViewById(R.id.study2_line1_layout);
		line_layout[2] = (LinearLayout) findViewById(R.id.study2_line2_layout);
		line_layout[3] = (LinearLayout) findViewById(R.id.study2_line3_layout);
		line_layout[4] = (LinearLayout) findViewById(R.id.study2_line4_layout);
		line_layout[5] = (LinearLayout) findViewById(R.id.study2_line5_layout);
		line_layout[6] = (LinearLayout) findViewById(R.id.study2_line6_layout);
		line_layout[7] = (LinearLayout) findViewById(R.id.study2_line7_layout);
		line_layout[8] = (LinearLayout) findViewById(R.id.study2_line8_layout);
		line_layout[9] = (LinearLayout) findViewById(R.id.study2_line9_layout);
		line_layout[10] = (LinearLayout) findViewById(R.id.study2_line10_layout);
		line_layout[11] = (LinearLayout) findViewById(R.id.study2_line11_layout);

		ok_img[0] = (ImageView) findViewById(R.id.study2_okImg0);
		ok_img[1] = (ImageView) findViewById(R.id.study2_okImg1);
		ok_img[2] = (ImageView) findViewById(R.id.study2_okImg2);
		ok_img[3] = (ImageView) findViewById(R.id.study2_okImg3);
		ok_img[4] = (ImageView) findViewById(R.id.study2_okImg4);
		ok_img[5] = (ImageView) findViewById(R.id.study2_okImg5);
		ok_img[6] = (ImageView) findViewById(R.id.study2_okImg6);
		ok_img[7] = (ImageView) findViewById(R.id.study2_okImg7);
		ok_img[8] = (ImageView) findViewById(R.id.study2_okImg8);
		ok_img[9] = (ImageView) findViewById(R.id.study2_okImg9);
		ok_img[10] = (ImageView) findViewById(R.id.study2_okImg10);
		ok_img[11] = (ImageView) findViewById(R.id.study2_okImg11);

		intro_text[0] = (TextView) findViewById(R.id.study2_introText0);
		intro_text[1] = (TextView) findViewById(R.id.study2_introText1);
		intro_text[2] = (TextView) findViewById(R.id.study2_introText2);
		intro_text[3] = (TextView) findViewById(R.id.study2_introText3);
		intro_text[4] = (TextView) findViewById(R.id.study2_introText4);
		intro_text[5] = (TextView) findViewById(R.id.study2_introText5);
		intro_text[6] = (TextView) findViewById(R.id.study2_introText6);
		intro_text[7] = (TextView) findViewById(R.id.study2_introText7);
		intro_text[8] = (TextView) findViewById(R.id.study2_introText8);
		intro_text[9] = (TextView) findViewById(R.id.study2_introText9);
		intro_text[10] = (TextView) findViewById(R.id.study2_introText10);
		intro_text[11] = (TextView) findViewById(R.id.study2_introText11);

	}

	/**
	 * 跳至扩展页
	 * 
	 * @param i
	 */
	private void jumpToExtend(int i) {
		// TODO Auto-generated method stub
		setContentView(R.layout.study_extend);
		currPageNum = 2;
		viewInit_extend();

		lastStudyIndex = i;
		studyTheKeyOnce(lastStudyIndex);
	}

	private void viewInit_extend() {
		// TODO Auto-generated method stub
		specialKeyLayout1 = (LinearLayout) findViewById(R.id.study_extend_keylayout1);
		specialKeyLayout2 = (LinearLayout) findViewById(R.id.study_extend_keylayout2);
		specialImg1 = (ImageView) findViewById(R.id.study_extend_keyImage1);
		specialImg2 = (ImageView) findViewById(R.id.study_extend_keyImage2);
		
		bgbm.recycle();
		bgbm = FileUtil.readBitMap(this, R.drawable.specialstudybg);
		findViewById(R.id.study_extend_layout).setBackgroundDrawable(new BitmapDrawable(bgbm));

		keyInfos = keyInfos_extend;

	}

	/**
	 * 结束学习
	 */
	private void finishStudy() {
		SLog.d("ssc", "结束学习");
		isInStudy = false;
		SLog.d("ssc", "isInStudy==" + isInStudy);
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				int returnCode = CAEProtocal.finishStudy();
			}

		}.start();
	}

	private void jumpToNextStep() {
		switch (currPageNum) {// 当前页
		case 0:// 第一页
			if (lastStudyIndex == 0) {
				new AlertDialog.Builder(StudyActivity.this)
						.setTitle("提示")
						.setMessage("您还未学习任何按键，请学习完成后再进入下一步")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

									}
								}).show();
			} else {
				finishStudy();
				new AlertDialog.Builder(StudyActivity.this)
						.setTitle("提示")
						.setMessage("还有部分按键未学习，确定进入下一步？")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

										Intent intent = new Intent();
										intent.setClass(StudyActivity.this,
												HDMIActivity.class);
										startActivity(intent);

										getStateThread = null;
										prapareThread = null;
										onceStudyThread = null;
										twiceStudyThread = null;
										isActivityAlive = false;

									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										prapareStudy();
									}
								}).show();
			}
			break;
		case 1:// 第二页
			finishStudy();
			if (lastStudyIndex < keyInfos2.size() - 1) {
				new AlertDialog.Builder(StudyActivity.this)
						.setTitle("提示")
						.setMessage("还有部分按键未学习，确定进入下一步？")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

										getStateThread = null;
										prapareThread = null;
										onceStudyThread = null;
										twiceStudyThread = null;
										isActivityAlive = false;

										Intent intent = new Intent();
										intent.setClass(StudyActivity.this,
												HDMIActivity.class);
										startActivity(intent);
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										prapareStudy();
									}
								}).show();
			} else {
				finishStudy();
				getStateThread = null;
				prapareThread = null;
				onceStudyThread = null;
				twiceStudyThread = null;
				isActivityAlive = false;

				Intent intent = new Intent();
				intent.setClass(StudyActivity.this, HDMIActivity.class);
				startActivity(intent);
			}
			break;
		case 2:// 扩展页
			if (isInStudy) {
				finishStudy();
			}
			Intent intent = new Intent();
			intent.setClass(StudyActivity.this, HDMIActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (event.getKeyCode()) {
		case KeyEvent.KEYCODE_BACK:
			if (isInStudy) {
				finishStudy();
			}
			break;
		case 12:// 5
			debugBuffer = new StringBuffer();
			debugBuffer.append("l");
			SLog.d("ssc", "11-----debugBuffer==" + debugBuffer);
			return false;

		case 13:// 6
			if (debugBuffer != null) {
				debugBuffer.append("o");
				SLog.d("ssc", "13-----debugBuffer==" + debugBuffer);
				return false;
			}
			break;

		case 11:// 4
			if (debugBuffer != null) {
				debugBuffer.append("g");
				TroubleShooting troubleShooting = new TroubleShooting(
						StudyActivity.this, debugBuffer);
				debugBuffer = new StringBuffer();

				return false;
			}

			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			if (isInStudy) {// 正在学习中
				ok_img[lastStudyIndex].setImageResource(R.drawable.nostudykey);
				ok_img[lastStudyIndex].setVisibility(View.VISIBLE);
				intro_text[lastStudyIndex].setVisibility(View.INVISIBLE);
				line_layout[lastStudyIndex].setBackgroundDrawable(null);

				lastStudyIndex++;
				if (lastStudyIndex < keyInfos.size()) {
					studyTheKeyOnce(lastStudyIndex);
				} else {
					if (currPageNum == 0) {
						jumpToStudy2(0);
						studyTheKeyOnce(lastStudyIndex);
					} else if (currPageNum == 1) {
						jumpToExtend(0);
					} else {
						finishStudy();
						Intent intent = new Intent();
						RemoteManager.setStudyState(StudyActivity.this, true);
						intent.setClass(StudyActivity.this,
								FinishActivity.class);
						startActivity(intent);
					}
				}

			}
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		SLog.d("ssc", "StudyActivity------------onDestroy()");
		// 移出管理栈
		ActivityStackControlUtil.remove(this);

		getStateThread = null;
		prapareThread = null;
		onceStudyThread = null;
		twiceStudyThread = null;
		isActivityAlive = false;
		keyInfos = null;
		keyInfos1 = null;
		keyInfos2 = null;
		keyInfos_extend = null;
		
		line_layout = null;
		ok_img = null;
		intro_text = null;
		specialKeyLayout1 = null;
		specialKeyLayout2 = null;
		specialImg1 = null;
		specialImg2 = null;
		mpDialog = null;
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		SLog.d("ssc", "StudyActivity------------finish()");

		super.finish();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		SLog.d("ssc", "StudyActivity------------onPause()");
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		SLog.d("ssc", "StudyActivity------------onRestart()");
		super.onRestart();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		SLog.d("ssc", "StudyActivity------------onStart()");
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		SLog.d("ssc", "StudyActivity------------onStop()");
		super.onStop();
		finish();
	}
}
